/**
 * 
 */
package br.ufpe.cin.plebeia.persistence.hibernateDao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.ufpe.cin.plebeia.dao.BasicDao;
import br.ufpe.cin.plebeia.model.EntidadePersistente;
import br.ufpe.cin.plebeia.util.HibernateUtil;

/**
 * @author bruno
 * 
 */
public class HibernateBasicDao<T extends EntidadePersistente> implements
		BasicDao<T> {
	private final Class<T> persistentClass;

	public HibernateBasicDao(Class<T> klass) {
		this.persistentClass = klass;
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	public void save(T entidade) {

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		session.saveOrUpdate(entidade);

		tx.commit();
		session.close();

	}

	public void update(T entidade) {

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		session.saveOrUpdate(entidade);

		tx.commit();
		session.close();

	}

	public void delete(T entidade) {

		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		session.delete(entidade);

		tx.commit();
		session.close();

	}

	@SuppressWarnings("unchecked")
	public T retrieve(Long id) {

		Session session = HibernateUtil.getSession();

		T entidade = (T) session.get(getPersistentClass(), id);

		session.close();
		return entidade;
	}

	@SuppressWarnings("unchecked")
	public List<T> retrieveAll() {
		Session session = HibernateUtil.getSession();

		List list = session.createCriteria(getPersistentClass()).list();
		session.close();
		return list;

	}

}
